package com.trex.modules.tbl.lineform.web;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trex.modules.tbl.dw.service.TblDwProService;
import com.trex.modules.tbl.entity.ServerBxConfig;
import com.trex.modules.tbl.entity.TblXdLjzyjl;
import com.trex.modules.tbl.kclb.service.TblZdKcyyService;
import com.trex.modules.tbl.lineform.service.TblXdZxxdctzdService;
import com.trex.modules.tbl.replyform.service.TblXdJxchsdService;
import com.trex.modules.tbl.service.TblXdLjzyjlService;
import com.trex.modules.tbl.workerplace.dao.TblZdWorkerdzDao;
import com.trex.modules.utils.JsonGenerator;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.trex.modules.tbl.lineform.entity.TblXdZxxdctzd;
import com.trex.modules.utils.TimeUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static com.trex.modules.utils.JsonSenderUtil.sendJsonWithHttpClient;


/**
 * 站修线倒车通知单Controller
 * @author jy
 * @version 2023-02-04
 */
@Controller
@RequestMapping(value = "/tbl/lineform/tblXdZxxdctzd")
public class   TblXdZxxdctzdController extends BaseController {


	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	@Autowired
	private TblXdZxxdctzdService tblXdZxxdctzdService;
	@Autowired
	private TblDwProService tblDwProService;
	@Autowired
	private TblXdLjzyjlService tblXdLjzyjlService;
	@Autowired
	private TblXdJxchsdService tblXdJxchsdService;
	@Autowired
	private TblZdWorkerdzDao tblZdWorkerdzDao;
	@Autowired
	private TblZdKcyyService tblZdKcyyService;

	private final ServerBxConfig serverBxConfig;

    public TblXdZxxdctzdController(ServerBxConfig serverBxConfig) {
        this.serverBxConfig = serverBxConfig;
    }


    /**
	 * 获取数据
	 */
	@ModelAttribute
	public TblXdZxxdctzd get(String recId, boolean isNewRecord) {
		return tblXdZxxdctzdService.get(recId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:view")
	@RequestMapping(value = {"list", ""})
	public String list( @RequestParam(value = "userid", required = false) String userid,
						@RequestParam(value = "postid", required = false) String postid,TblXdZxxdctzd tblXdZxxdctzd, Model model,HttpServletRequest request) {
		String I_IP_ADDR = request.getRemoteHost();
		logger.info("Received userid:\"!!!!!!!!!!!!!!!!!!!!!!!!!\"+\"______\"+ " + userid);
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();
			// 将 userid 添加到模型中或者在逻辑中使用
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		tblXdZxxdctzd.setAddTime(TimeUtils.getCurrentDate());
		
		model.addAttribute("tblXdZxxdctzd", tblXdZxxdctzd);
		
		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);

		List<TblXdZxxdctzd> lineList2 = new ArrayList<>();
		model.addAttribute("lineListByStation", lineList2);

		return "modules/tbl/lineform/tblXdZxxdctzdList2";
	}


	@RequestMapping(value = {"list1", ""})
	public String list1( @RequestParam(value = "userid", required = false) String userid,
						@RequestParam(value = "postid", required = false) String postid,TblXdZxxdctzd tblXdZxxdctzd, Model model,HttpServletRequest request) {

		String I_IP_ADDR = request.getRemoteHost();
		// 获取当前时间
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);



		model.addAttribute("tblXdZxxdctzd", tblXdZxxdctzd);

		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId) ;
		model.addAttribute("lineList", lineList);

		List<TblXdZxxdctzd> lineList2 = new ArrayList<>();
		model.addAttribute("lineListByStation", lineList2);

		return "modules/tbl/lineform/tblXdZxxdctzdList1";
	}



	
	/**
	 * 查询列表数据
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TblXdZxxdctzd> listData(TblXdZxxdctzd tblXdZxxdctzd, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		tblXdZxxdctzd.setPage(new Page<>(request, response));
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		tblXdZxxdctzd.setUserid(userId);
		logger.info("9999999999999999999999+_____" + userId);
		StringBuilder strWhere = new StringBuilder();

		if (tblXdZxxdctzd.getDqczbh() != null && !Objects.equals(tblXdZxxdctzd.getDqczbh(), "")) {
			strWhere.append(" AND A.DQCZBH = '").append(tblXdZxxdctzd.getDqczbh()).append("'");
		}

		// 附加条件：Dqxlbh
		if (tblXdZxxdctzd.getDqxlbh() != null && !Objects.equals(tblXdZxxdctzd.getDqxlbh(), "")) {
			strWhere.append(" AND A.DQXLBH = '").append(tblXdZxxdctzd.getDqxlbh()).append("'");
		}

		 strWhere = new StringBuilder(" AND A.DQCDBH IN ( SELECT CDBH FROM VZD_LJCDDZ WHERE WORKER_ID = '" + userId + "') ");
//		if(StringUtils.isEmpty(tblXdZxxdctzd.getDeviceNo())) {
			String shift = tblXdZxxdctzd.getRemark(); //班制
			Date addTime = tblXdZxxdctzd.getAddTime(); //日期
			if(addTime != null) {
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				formatter.format(addTime);
				Calendar cal = new GregorianCalendar();
				
				if("1".equals(shift)){
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					//夜班
					cal.setTime(addTime);
					cal.add(Calendar.DATE, -1);
					Date addTimeE = cal.getTime();
					String timeEnded= null;
					String timeGte = formatter.format(addTime);
					String timeLte = formatter.format(addTimeE);
					timeEnded = timeLte.substring(0, 10)+" 19:00:00";
					timeGte = timeGte.substring(0, 10)+" 08:00:00";
					timeLte = timeEnded;

					tblXdZxxdctzd.setAddTime_gte(format.parse(timeLte));
					tblXdZxxdctzd.setAddTime_lte(format.parse(timeGte));
				}else{
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					//白班
					cal.setTime(addTime);
					cal.add(Calendar.DATE, 0);
					Date addTimeE = cal.getTime();
					String timeGte = formatter.format(addTime);
					String timeLte = formatter.format(addTimeE);
					timeGte = formatter.format(addTime).substring(0, 10)+" 08:00:00";
					timeLte = timeGte.substring(0, 10)+" 19:00:00";
					tblXdZxxdctzd.setAddTime_gte(format.parse(timeGte));
					tblXdZxxdctzd.setAddTime_lte(format.parse(timeLte));
				}
				tblXdZxxdctzd.setAddTime(null);
				tblXdZxxdctzd.getSqlMap().put("extWhere", strWhere);
				Page<TblXdZxxdctzd> page = tblXdZxxdctzdService.findPage(tblXdZxxdctzd);
				return page;
			}

return null;
	}
	@RequestMapping(value = "listInfo")
	@ResponseBody
	public Page<TblXdZxxdctzd> listInfo(TblXdZxxdctzd tblXdZxxdctzd, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		tblXdZxxdctzd.setPage(new Page<>(request, response));
		tblXdZxxdctzd.setRemark("3");
		if (tblXdZxxdctzd.getRecId() != null){

			Page<TblXdZxxdctzd> page = tblXdZxxdctzdService.findPage(tblXdZxxdctzd);
			return page;
		}

		return null;
	}
	/**
	 * 新增站修线倒车通知单表
	 */
	@PostMapping(value = "insertData")
	@ResponseBody
	public String insertData(TblXdZxxdctzd tblXdZxxdctzd, HttpServletRequest request) throws Exception {
		HashMap<String, String> paramMap = new HashMap<>();
		// 创建一个 ObjectMapper 实例
		long timestamp = System.currentTimeMillis();
		String timestampWithLast4Millis1 = timestamp + String.format("%04d", timestamp % 10000);
		// SysInfo 数据
		// 构建 SysInfo 数据
		Map<String, Object> sysInfo1 = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM234",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis1
		);

// BODY 表的行数据（作为 Map，而不是 List）
		List<Map<String, Object>> bodyRows = List.of(
				Map.of(
						"OPERATION_FLAG", "I",
						"STATION_TRACK", tblXdZxxdctzd.getDqxlbh(),
						"WAGONNO", ""
				)
		);

// 构建 Tables 数据
		Map<String, Object> tables1 = Map.of(
				"BODY", bodyRows
		);

// 构建最终的 JSON 数据结构
		Map<String, Object> finalData = Map.of(
				"SysInfo", sysInfo1,
				"Tables", tables1
		);

// 打印或返回 JSON
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonMap = objectMapper.writeValueAsString(finalData);
		// 发送请求并获取响应请求现车
//		String url = "http://172.16.16.122:8083/bx";
//		String url = "http://172.16.16.36:8084/bx";

		String url = "http://"+serverBxConfig.getAddress()+":"+serverBxConfig.getPort()+"/bx";

		String jsonResponse = HttpClientUtils.ajaxPostJson(url, jsonMap);
		logger.info("jsonResponse22222222222222: " + jsonResponse  + url);


		//调用存储过程
		return renderResult(Global.TRUE, text("保存站修线倒车通知单成功！"));
	}



	/**
	 * 查看编辑表单
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:view")
	@RequestMapping(value = "form")
	public String form(TblXdZxxdctzd tblXdZxxdctzd, Model model) {
		List<TblXdZxxdctzd> rlcList = tblZdKcyyService.findrepairLine(new TblXdZxxdctzd());
		model.addAttribute("rlcList", rlcList);
		model.addAttribute("tblXdZxxdctzd", tblXdZxxdctzd);
		model.addAttribute("ids", tblXdZxxdctzd.getIds());
		return "modules/tbl/lineform/tblXdZxxdctzdForm";
	}

	/**
	 * 保存数据
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TblXdZxxdctzd tblXdZxxdctzd, HttpServletRequest request) throws JsonProcessingException {
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		String destName = tblXdZxxdctzdService.selectdest(tblXdZxxdctzd.getDest());
		String[] zxdd = tblXdZxxdctzd.getZXDD().split(",");
		String cczkCode =tblXdZxxdctzd.getCczk();
		tblXdZxxdctzd.setDestName(destName);
		tblXdZxxdctzd.setUserName(userName);
		tblXdZxxdctzd.setCczk(cczkCode);
		tblXdZxxdctzd.setUserid(userId);
		if (cczkCode.equals("2")){
			tblXdZxxdctzd.setZXDD(zxdd[0]);
			List<TblXdZxxdctzd> rlcList = tblZdKcyyService.findrepairLine(new TblXdZxxdctzd());
			for (TblXdZxxdctzd xdZxxdctzd : rlcList) {
				if(xdZxxdctzd.getXLBH().equals(zxdd[0])){
					tblXdZxxdctzd.setZxddName(xdZxxdctzd.getXLMC());
					break;
				}
			}
		}else {
			tblXdZxxdctzd.setZXDD("");
			tblXdZxxdctzd.setZxddName("");
		}
		if (tblXdZxxdctzd.getIds() != null && !tblXdZxxdctzd.getIds().trim().isEmpty()) {
			// 批量数据修改ID处理
			String[] strings = tblXdZxxdctzd.getIds().split(",");
			for (String id : strings) {
				String wagonno = tblXdZxxdctzdService.selectWagonno(id);
				String deviceId = tblXdZxxdctzdService.selectDeviceid(id);
                String tzdbh = tblXdZxxdctzdService.selectTzdbh(id);
				String seq = tblXdZxxdctzdService.selectSeq(id);
				tblXdZxxdctzd.setWagonno(wagonno);
				tblXdZxxdctzd.setDeviceNo(deviceId);
				tblXdZxxdctzd.setRecId(id);
				tblXdZxxdctzd.setTzdbh(tzdbh);
				tblXdZxxdctzd.setJxcbh(null);
				tblXdZxxdctzd.setSeq(seq);

				tblXdZxxdctzdService.save(tblXdZxxdctzd);

				long timestamp = System.currentTimeMillis();
				// 将时间戳转换为 Date 对象
				Date date = new Date(timestamp);

				// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				String formattedDate = sdf.format(date);
				String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
				ObjectMapper objectMapper = new ObjectMapper();

				/*NEM218*/
				Map<String, Object> sysInfo1 = Map.of(
						"Flag", 0,
						"Msg", "",
						"SvcName", "NEM218",
						"UUID", timestampWithLast4Millis
				);

				// BODY 表的 Columns 数据
				List<Map<String, String>> bodyColumns1 = List.of(
						Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
						Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录ID"),
						Map.of("Name", "POUR_OUT_TIME", "DataType", "S", "Caption", "倒出时间"),
						Map.of("Name", "IS_OUT_STAGE", "DataType", "S", "Caption", "是否出场"),
						Map.of("Name", "DEST", "DataType", "S", "Caption", "去向"),
						Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人"),
						Map.of("Name", "CONFM_NUMBER", "DataType", "S", "Caption", "确认人"),
						Map.of("Name", "PROCESSING_TIME", "DataType", "S", "Caption", "办理时间"),
						Map.of("Name", "CCZK", "DataType", "S", "Caption", "出场状况"),
						Map.of("Name", "ZXZZ", "DataType", "S", "Caption", "专项整治"),
						Map.of("Name", "SFJF", "DataType", "S", "Caption", "是否禁峰"),
						Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号"),
						Map.of("Name", "ZXDD", "DataType", "S", "Caption", "转修地点"),
						Map.of("Name", "VEHICLEREPAIRSTATUS", "DataType", "S", "Caption", "修程")
				);

				// BODY 表的 Rows 数据
				List<List<Object>> bodyRows1 = new ArrayList<>();
				List<Object> row1 = new ArrayList<>();

// 向 row 添加元素
				row1.add("I");
				row1.add(tblXdZxxdctzd.getJxcbh() != null ? tblXdZxxdctzd.getJxcbh() : "");
				row1.add(formattedDate != null ? formattedDate : "");
				row1.add(tblXdZxxdctzd.getIsOutStage() != null ? tblXdZxxdctzd.getIsOutStage() : "");
				row1.add(tblXdZxxdctzd.getDest() != null ? tblXdZxxdctzd.getDest() : "");
				row1.add(userName != null ? userName : "");
				row1.add(userName != null ? userName : "");
				row1.add(formattedDate != null ? formattedDate : "");
				row1.add(tblXdZxxdctzd.getCczk() != null ? tblXdZxxdctzd.getCczk() : "");
				row1.add(tblXdZxxdctzd.getZxzz() != null ? tblXdZxxdctzd.getZxzz() : "");
				row1.add(tblXdZxxdctzd.getIsNopeak() != null ? tblXdZxxdctzd.getIsNopeak() : "");
				row1.add(tblXdZxxdctzd.getWagonno() != null ? tblXdZxxdctzd.getWagonno() : "");
				row1.add(tblXdZxxdctzd.getZXDD() != null ? tblXdZxxdctzd.getZXDD() : "");
				row1.add(tblXdZxxdctzd.getVehicleRepairStatus() != null ? tblXdZxxdctzd.getVehicleRepairStatus() : "");



// 将 row 添加到 bodyRows 中
				bodyRows1.add(row1);
// 转换为 key-value 结构的 map
				List<Map<String, Object>> keyValueMessage1 = new ArrayList<>();
				for (List<Object> rowData1 : bodyRows1) {
					Map<String, Object> rowMap1 = new HashMap<>();
					for (int j = 0; j < bodyColumns1.size(); j++) {
						String key = bodyColumns1.get(j).get("Name");
						Object value = rowData1.get(j);
						rowMap1.put(key, value);
					}
					keyValueMessage1.add(rowMap1);
				}


				// 构建最终的 Tables 结构
				Map<String, Object> tables1 = Map.of(
						"BODY", keyValueMessage1
				);

				// 构建最终的电文结构
				Map<String, Object> finalMessage1 = Map.of(
						"SysInfo", sysInfo1,
						"Tables", tables1
				);

				// 使用 Jackson 将 Map 转换为 JSON 字符串
				String json1=objectMapper.writeValueAsString(finalMessage1);

				logger.info("@@@@@@@@@@@@@@@" + json1);

				sendJsonWithHttpClient(serverBxConfig.getAddress(), serverBxConfig.getPort(), serverBxConfig.getMethod(), json1);
			}
		} else {
			tblXdZxxdctzd.setJxcbh(null);
			tblXdZxxdctzdService.save(tblXdZxxdctzd);
			long timestamp = System.currentTimeMillis();
			// 将时间戳转换为 Date 对象
			Date date = new Date(timestamp);

			// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String formattedDate = sdf.format(date);
			String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
			ObjectMapper objectMapper = new ObjectMapper();

			/*NEM218*/
			Map<String, Object> sysInfo1 = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM218",
					"UUID", timestampWithLast4Millis
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns1 = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录ID"),
					Map.of("Name", "POUR_OUT_TIME", "DataType", "S", "Caption", "倒出时间"),
					Map.of("Name", "IS_OUT_STAGE", "DataType", "S", "Caption", "是否出场"),
					Map.of("Name", "DEST", "DataType", "S", "Caption", "去向"),
					Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人"),
					Map.of("Name", "CONFM_NUMBER", "DataType", "S", "Caption", "确认人"),
					Map.of("Name", "PROCESSING_TIME", "DataType", "S", "Caption", "办理时间"),
					Map.of("Name", "CCZK", "DataType", "S", "Caption", "出场状况"),
					Map.of("Name", "ZXZZ", "DataType", "S", "Caption", "专项整治"),
					Map.of("Name", "SFJF", "DataType", "S", "Caption", "是否禁峰"),
					Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号"),
					Map.of("Name", "ZXDD", "DataType", "S", "Caption", "转修地点"),
					Map.of("Name", "VEHICLEREPAIRSTATUS", "DataType", "S", "Caption", "修程")

			);
			// BODY 表的 Rows 数据
			List<List<Object>> bodyRows1 = new ArrayList<>();
			List<Object> row1 = new ArrayList<>();

// 向 row 添加元素
			row1.add("I");
			row1.add(tblXdZxxdctzd.getJxcbh() != null ? tblXdZxxdctzd.getJxcbh() : "");
			row1.add(formattedDate != null ? formattedDate : "");
			row1.add(tblXdZxxdctzd.getIsOutStage() != null ? tblXdZxxdctzd.getIsOutStage() : "");
			row1.add(tblXdZxxdctzd.getDest() != null ? tblXdZxxdctzd.getDest() : "");
			row1.add(userName != null ? userName : "");
			row1.add(userName != null ? userName : "");
			row1.add(formattedDate != null ? formattedDate : "");
			row1.add(tblXdZxxdctzd.getCczk() != null ? tblXdZxxdctzd.getCczk() : "");
			row1.add(tblXdZxxdctzd.getZxzz() != null ? tblXdZxxdctzd.getZxzz() : "");
			row1.add(tblXdZxxdctzd.getIsNopeak() != null ? tblXdZxxdctzd.getIsNopeak() : "");
			row1.add(tblXdZxxdctzd.getWagonno() != null ? tblXdZxxdctzd.getWagonno() : "");
			row1.add(tblXdZxxdctzd.getZXDD() != null ? tblXdZxxdctzd.getZXDD() : "");
			row1.add(tblXdZxxdctzd.getVehicleRepairStatus() != null ? tblXdZxxdctzd.getVehicleRepairStatus() : "");



// 将 row 添加到 bodyRows 中
			bodyRows1.add(row1);
// 转换为 key-value 结构的 map
			List<Map<String, Object>> keyValueMessage1 = new ArrayList<>();
			for (List<Object> rowData1 : bodyRows1) {
				Map<String, Object> rowMap1 = new HashMap<>();
				for (int j = 0; j < bodyColumns1.size(); j++) {
					String key = bodyColumns1.get(j).get("Name");
					Object value = rowData1.get(j);
					rowMap1.put(key, value);
				}
				keyValueMessage1.add(rowMap1);
			}


			// 构建最终的 Tables 结构
			Map<String, Object> tables1 = Map.of(
					"BODY", keyValueMessage1
			);

			// 构建最终的电文结构
			Map<String, Object> finalMessage1 = Map.of(
					"SysInfo", sysInfo1,
					"Tables", tables1
			);

			// 使用 Jackson 将 Map 转换为 JSON 字符串
			String json1=objectMapper.writeValueAsString(finalMessage1);
			logger.info("@@@@@@@@@@@@@@@" + json1);

			String s11 = sendJsonWithHttpClient(serverBxConfig.getAddress(), serverBxConfig.getPort(), serverBxConfig.getMethod(), json1);
// 处理单条记录
		}
			return renderResult(Global.TRUE, text("保存站修线倒车通知单成功！"));


	}
	
	/**
	 * 删除数据
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(String jhhString) {
		try {
			tblXdZxxdctzdService.delete(jhhString);
			return renderResult(Global.TRUE, text("删除成功"));
		} catch (Exception e) {
			return renderResult(Global.FALSE, e.getMessage());
		}
	}
	
	/**
	 * 站修线倒车通知单列检调度确认
	 * @throws SQLException 
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:edit")
		@PostMapping(value = "confirm")
		@ResponseBody
		public String confirm(String ids, HttpServletRequest request) throws SQLException{
			try {
				tblXdZxxdctzdService.confirm(ids,request);
				return renderResult(Global.TRUE, text("确认成功"));
			} catch (Exception e) {
				return renderResult(Global.FALSE, e.getMessage());
			}
		}
	/**
	 * 站修线倒车通知单列检调度撤销
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:edit")
	@PostMapping(value = "cancel")
	@ResponseBody
	public String cancel(String ids,  HttpServletRequest request) throws SQLException {
		try {
			tblXdZxxdctzdService.cancel(ids,request);
			return renderResult(Global.TRUE, text("撤销成功"));
		} catch (Exception e) {
			return renderResult(Global.FALSE, e.getMessage());
		}
	}
	/**
	 * 调度确认查询列表
	 */
	//@RequiresPermissions("tbl:lineform:tblXdZxxdctzd:view")
	@RequestMapping(value = {"list2", ""})
	@Transactional
	public String list2(@RequestParam(value = "userid", required = false) String userid,
						@RequestParam(value = "postid", required = false) String postid,TblXdZxxdctzd tblXdZxxdctzd, Model model,HttpServletRequest request) {
		int hours = new Date().getHours();
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();

		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		model.addAttribute("tblXdZxxdctzd", tblXdZxxdctzd);

		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);
		List<TblXdZxxdctzd> lineList2 = new ArrayList<>();
		model.addAttribute("lineListByStation", lineList2);
		return "modules/tbl/lineform/tblXdZxxdctzdList";
	}

	/**
	 * 调度确认查询列表数据
	 */
// @RequiresPermissions("tbl:lineform:tblXdZxxdctzd:view")
	@SneakyThrows
	@RequestMapping(value = "listData2")
	@ResponseBody
	public Page<TblXdZxxdctzd> listData2(TblXdZxxdctzd tblXdZxxdctzd, HttpServletRequest request, HttpServletResponse response) {
		tblXdZxxdctzd.setPage(new Page<>(request, response));
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		StringBuilder strWhere = new StringBuilder();

		// 时间条件
		if (tblXdZxxdctzd.getStartTime() != null && tblXdZxxdctzd.getEndTime() != null) {

			if (userId != null) {
				// 基础条件
				strWhere.append(" AND DELE_FLAG = '0' ")
						.append("AND A.DQCDBH IN (SELECT CDBH FROM VZD_LJCDDZ WHERE WORKER_ID = '")
						.append(userId).append("')");

				if (tblXdZxxdctzd.getDqczbh() != null && !Objects.equals(tblXdZxxdctzd.getDqczbh(), "")) {
					strWhere.append(" AND A.DQCZBH = '").append(tblXdZxxdctzd.getDqczbh()).append("'");
				}

				// 附加条件：Dqxlbh
				if (tblXdZxxdctzd.getDqxlbh() != null&& !Objects.equals(tblXdZxxdctzd.getDqxlbh(), "")) {
					strWhere.append(" AND A.DQXLBH = '").append(tblXdZxxdctzd.getDqxlbh()).append("'");
				}

				// 附加条件：Wagonno
				if (tblXdZxxdctzd.getWagonno() != null && !tblXdZxxdctzd.getWagonno().isEmpty()) {
					strWhere.append(" AND A.WAGONNO LIKE '%").append(tblXdZxxdctzd.getWagonno()).append("%'");
				}


				String startTime = new SimpleDateFormat(DATE_FORMAT).format(tblXdZxxdctzd.getStartTime());
				String endTime = new SimpleDateFormat(DATE_FORMAT).format(tblXdZxxdctzd.getEndTime());
				strWhere.append(" AND A.ADD_TIME BETWEEN '").append(startTime).append("' AND '").append(endTime).append("'");


				tblXdZxxdctzd.getSqlMap().put("extWhere", strWhere.toString());
			}

			// 查询并记录操作耗时
			long startTime = System.currentTimeMillis();
			Page<TblXdZxxdctzd> result = tblXdZxxdctzdService.findPage(tblXdZxxdctzd);
			logger.info("Operation completed in " + (System.currentTimeMillis() - startTime) + "ms");
			return result;
		}
		return null;
	}



	
	/**
	 * 线路字典数据查询
	 */
	@RequestMapping(value = {"getAllLineList", ""})
	public List<TblXdLjzyjl> getAllLineList(String stationCode){
		List<TblXdLjzyjl> lineListByStation = tblXdZxxdctzdService.getAllLineListByStation(stationCode, UserUtils.getUser().getUserCode());
		return lineListByStation;
	}

	/**
	 * 部分线路字典数据查询
	 */
	//@RequiresPermissions("tbl:replyform:tblXdJxchsd:view")
	@RequestMapping(value = {"getSomeLineList", ""})
	public List<TblXdLjzyjl> getSomeLineList(String stationCode){
		List<TblXdLjzyjl> lineListByStation = tblXdZxxdctzdService.getSomeLineListByStation();
		return lineListByStation;
	}
	/*M2NE45*/

	@CrossOrigin(origins = {"http://172.16.16.129:5080", "http://172.16.16.200:5080"})   // 允许的请求来源
	@PostMapping("/receiveInfo")
	public ResponseEntity<String> receiveInfo(@RequestBody JSONObject json) throws Exception {
		// 打印接收到的 JSON 数据
		logger.info("Received JSON:&&&&&&&&&&&&&&&&&&&&&&&&&& " + json.toJSONString());

		tblXdJxchsdService.receiveInfo(json);

		// 返回接收到的数据
		return ResponseEntity.ok("success");
	}
	@CrossOrigin(origins = {"http://172.16.16.129:5080", "http://172.16.16.200:5080"})  // 允许的请求来源
	@PostMapping("/receiveCar")
	public ResponseEntity<String> receiveCar(@RequestBody JSONObject json) throws Exception {
		// 打印接收到的 JSON 数据
		logger.info("Received JSON: !!!!!!!!!!!!!!!!!!!!!!!!!!!!" + json.toJSONString());
		tblXdZxxdctzdService.receiveCar(json);

		// 返回接收到的数据
		return ResponseEntity.ok("success");
	}
}